<template>
  <view class="login-container" :data-theme="theme()" :class="theme() || ''">
    <view class="wechatapp">
      <image
        class="logo-image"
        :src="setting.loginLogo || '/static/login-default.png'"
      ></image>
      <view class="d-c-c f30 gray3">{{ setting.name }}</view>
    </view>
    <view class="auth-title fb">{{ $lang(setting,'loginDesc') }}</view>
    <view class="auth-subtitle">{{$t('login.bind_phone_authorization')}} {{$t('login.better_service')}}</view>
    <view class="login-btn d-c-c">
      <!-- #ifdef MP-WEIXIN -->

      <template v-if="!mobile">
        <button
          v-if="wxPhone"
          class="theme-btn"
          open-type="getPhoneNumber"
          @getphonenumber="getUserInfo"
        >
          {{$t('login.one_click_login')}}
        </button>
        <button v-else class="theme-btn" @click="UserLogin()">{{$t('login.login_now')}}</button>
      </template>
      <button v-else class="theme-btn" @click="UserLogin">{{$t('login.one_click_login')}}</button>
      <!-- #endif -->
      <!-- #ifdef MP-ALIPAY -->
      <button
        :disabled="!isRead"
        @getAuthorize="onGetAuthorize"
        scope="userInfo"
        open-type="getAuthorize"
        size="default"
        class="login-btn-ali theme-btn"
      >
        {{$t('login.alipay_login')}}
      </button>
      <!-- #endif -->
    </view>
    <view @click="isRead = !isRead" class="d-s-s f-w gray6 mt20">
      <view
        class="icon iconfont icon-tijiaochenggong"
        :class="isRead ? 'active agreement' : 'agreement'"
      ></view>
      {{$t('login.agree_to_terms')}}<text class="dominant" @click="xieyi('service')"
        >《{{$t('login.user_agreement')}}》</text
      >{{$t('login.and')}}<text class="dominant" @click="xieyi('privacy')">《{{$t('login.privacy_policy')}}》</text>
    </view>
    <view class="no-login-btn d-a-c">
      <view class="f26 gray9" @click="toShops">{{$t('login.shop_login')}}</view>
      <view class="f26 gray9" @click="onNotLogin">{{$t('login.decline_login')}}</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      wxPhone: false,
      loading: true,
      background: "",
      listData: [],
      userId: "",
      mobile: true,
      isRead: false,
      setting: {
        loginDesc: "",
        loginLogo: "",
        name: "",
      },
      invitationId: 0,
    };
  },
  onLoad(e) {
    this.invitationId = uni.getStorageSync("invitationId")
      ? uni.getStorageSync("invitationId")
      : 0;
    let self = this;
    this.getCodeType();
    uni.getUserInfo({
      success: function (res) {
        // console.log(res)
        const userInfo = res.userInfo;
        console.log(userInfo);
        uni.login({
          provider: "weixin",
          success: (res) => {
            console.log("res-login", res); //获取到code
            self.code = res.code;
            // console.log('code', res.code);

            //请求登录接口
            if (res.errMsg == "login:ok") {
              var params = {
                code: self.code,
                nickname: userInfo.nickName,
                avatar: userInfo.avatarUrl,
              };
              self._postBody(
                "user/userWx/login",
                {
                  code: self.code,
                  source: "wx",
                  invitationId: self.invitationId,
                  refereeId: uni.getStorageSync("refereeId"),
                },
                (result) => {
                  self.userId = result.data.userId;
                  self.mobile = result.data.mobile;
                },
                false,
                () => {
                  self.loading = false;
                }
              );
            }
          },
        });
      },
    });
  },
  onShow() {
    this.wxPhone = uni.getStorageSync("wxPhone") || 0;
    //隐藏无效的返回按钮
    //   wx.hideHomeButton({
    //     complete:()=>{
    //     }
    //   })
    uni.setNavigationBarTitle({
      title: this.$t('login.login')
    })
  },
  methods: {
    xieyi(type) {
      this.gotoPage("/pages/webview/ue?type=" + type);
    },
    getCodeType() {
      let self = this;
      self._get("index/loginSetting", {}, (res) => {
        self.setting = res.data;
      });
    },
    onNotLogin: function () {
      this.gotoPage("/pages/index/index");
    },
    toShops(){
      this.gotoPage("/pages/login/shoplogin");
    },
    UserLogin() {
      let self = this;
      if (self.loading) {
        return;
      }
      if (!self.isRead) {
        uni.showToast({
          title: this.$t('login.please_agree'),
          icon: "none",
        });
        return;
      }
      uni.showLoading({
        title: this.$t('login.processing'),
        mask: true,
      });
      // 执行微信登录
      wx.login({
        success(res_login) {
          let url = "user/userWx/userLogin";
          let params = {
            code: res_login.code,
          };
          // 发送用户信息
          self._postBody(
            url,
            params,
            (result) => {
              // 记录token user_id
              uni.setStorageSync("token", result.data.token);
              uni.setStorageSync("userId", result.data.loginUserVo.userId);
              // 执行回调函数
              uni.navigateBack();
            },
            false,
            () => {
              uni.hideLoading();
            }
          );
        },
      });
    },
    getUserInfo: function (e) {
      let self = this;
      if (self.loading) {
        return;
      }
      if (!self.isRead) {
        uni.showToast({
          title:this.$t('login.please_agree'),
          icon: "none",
        });
        return;
      }
      if (e.detail.errMsg !== "getPhoneNumber:ok") {
        return false;
      }
      uni.showLoading({
        title: this.$t('login.processing'),
        mask: true,
      });
      wx.login({
        success(res_login) {
          let url = "user/userWx/bindMobile";
          let params = {
            code: res_login.code,
            userId: self.userId,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
          };
          // 发送用户信息
          self._post(
            url,
            params,
            (result) => {
              // 记录token user_id
              uni.setStorageSync("token", result.data.token);
              uni.setStorageSync("userId", result.data.loginUserVo.userId);
              // 执行回调函数
              uni.navigateBack();
              uni.switchTab({
                url: "/pages/user/index/index",
              });
            },
            false,
            () => {
              uni.hideLoading();
            }
          );
        },
      });

      // wx.getUserProfile({
      // 	lang: 'zh_CN',
      // 	desc: '用于完善会员资料',
      // 	success: (res) => {
      // 		if (res.errMsg !== 'getUserProfile:ok') {
      // 			return false;
      // 		}
      // 		uni.showLoading({
      // 			title: "正在登录",
      // 			mask: true
      // 		});
      // 		// 执行微信登录
      // 		uni.login({
      // 			success(res_login) {
      // 				// 发送用户信息
      // 				self._postBody('user/userWx/login', {
      // 					invitationId: self.invitationId,
      // 					code: res_login.code,
      // 					userInfo: res.rawData,
      // 					encrypted_data: encodeURIComponent(res.encryptedData),
      // 					iv: encodeURIComponent(res.iv),
      // 					signature: res.signature,
      // 					refereeId: uni.getStorageSync('refereeId')
      // 				}, result => {
      // 					// 记录token userId
      // 					uni.setStorageSync('token', result.data.token);
      // 					uni.setStorageSync('userId', result.data.loginUserVo.userId);
      // 					// 执行回调函数,没有上一页,不走回调直接跳转
      // 					// uni.navigateBack();
      //   uni.switchTab({
      //     url: '/pages/user/index/index'
      //   })
      // 				}, false, () => {
      // 					uni.hideLoading();
      // 				});
      // 			}
      // 		});
      // 	}
      // });
    },
    onGetAuthorize(res) {
      console.log("开始授权");
      let self = this;
      uni.login({
        provider: "alipay",
        success: function (loginRes) {
          console.log("sucss");
          uni.getUserInfo({
            provider: "alipay",
            success: function (infoRes) {
              self.aliPayLogin(loginRes, infoRes);
            },
          });
        },
        fail(err) {
          console.log(err);
        },
      });
    },
    aliPayLogin(loginRes, infoRes) {
      let self = this;
      console.log(loginRes); // 获取用户信息
      console.log(infoRes);
      uni.showLoading({
        title: this.$t('login.logging_in_in_progress'),
        mask: true,
      });
      self._post(
        "user/useralipay/login",
        {
          code: loginRes.code,
          avatar: infoRes.avatar,
          nickName: infoRes.nickName,
        },
        (result) => {
          // 记录token user_id
          console.log(result.data.token);
          uni.setStorageSync("token", result.data.token);
          uni.setStorageSync("userId", result.data.loginUserVo.userId);

          // 执行回调函数
          self.gotoPage("/pages/index/index", "redirect");
        },
        false,
        () => {
          self.gotoPage("/pages/index/index", "redirect");
        }
      );
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #fff;
}

.login-container {
  padding: 30rpx;
}

.wechatapp {
  padding: 120rpx 0 48rpx;
  margin-bottom: 72rpx;
  text-align: center;

  .logo-image {
    margin: 0 auto;
    margin-bottom: 20rpx;
    width: 145rpx;
    height: 145rpx;
    border-radius: 50%;
  }
}

.m-0-a {
  margin: 0 auto;
}

.wechatapp .header {
  width: 190rpx;
  height: 190rpx;
  border: 2px solid #fff;
  margin: 0rpx auto 0;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 1px 0px 5px rgba(50, 50, 50, 0.3);
}

.auth-title {
  color: #333333;
  font-size: 30rpx;
  margin-top: 170rpx;
  margin-bottom: 85rpx;
  text-align: center;
}

.auth-subtitle {
  color: #777;
  margin-bottom: 20rpx;
  font-size: 22rpx;
  text-align: center;
}

.login-btn {
  padding: 0 20rpx;
}

.login-btn button {
  width: 592rpx;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 30rpx;
  text-align: center;
  line-height: 88rpx;
}

.login-btn button.login-btn-ali {
  height: 88rpx;
  line-height: 88rpx;
  background: #1678ff;
  color: #fff;
  font-size: 30rpx;
  border-radius: 999rpx;
  text-align: center;
}

.no-login-btn {
  position: fixed;
  bottom: 220rpx;
  left: 0;
  width: 100%;
}

.agreement {
  border-radius: 50%;
  width: 28rpx;
  height: 28rpx;
  border: 1px solid #ccc;
  background: #fff;
  position: relative;
  margin-right: 10rpx;
  box-sizing: border-box;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18rpx;
  font-weight: bold;
}

.agreement.active {
  @include font_color("font_color_inverse");
  @include background_color("background_color");
  @include border_color("border_color");
}
</style>
